import store from "store"
import isEmpty from "lodash/isEmpty"

export async function authChecker() {
	
  const accessToken = store.getters.accessToken
  const refreshAt = store.getters.accessTokenRefreshAt
  const expiredAt = store.getters.accessTokenExpiredAt
  let dateTime = new Date().getTime()

  /**
   * Token is valid. token有效
   */
  if (accessToken && (dateTime < refreshAt)) {
    return true
  }

  /**
   * Token nearly expired but can still be refreshed.
   * then after refresh or login getting a new token.
   */
  if (accessToken && (dateTime >= refreshAt) && (dateTime) <= expiredAt) {
    logout() // clean local token.

    try {
      await store.dispatch('refresh') // get refreshed token
      return !isEmpty(store.getters.accessToken)
    } catch (err) {
      await store.dispatch('login') // get new token
      return !isEmpty(store.getters.accessToken)
    }
  }

  /**
   * Token expired and can not be refreshed.
   * then after login and get a new token.
   */
  if (accessToken && (dateTime > expiredAt)) {
    logout() // clean local token.
    return false
  }

  return false
}

export function setToken(tokenPayload) {//设置本地存储时间戳  token
  const accessToken = tokenPayload.access_token
  const accessTokenRefreshAt = new Date().getTime() + tokenPayload.refresh_at * 1000
  const accessTokenExpiredAt = new Date().getTime() + tokenPayload.expired_at * 1000
  uni.setStorageSync('access_token', accessToken)
  uni.setStorageSync('access_token_refresh_at', accessTokenRefreshAt)
  uni.setStorageSync('access_token_expired_at', accessTokenExpiredAt)
}

export function getToken() {
  return uni.getStorageSync('access_token')
}

export function getTokenRefreshAt() {
  return uni.getStorageSync('access_token_refresh_at')
}

export function getTokenExpiredAt() {
  return uni.getStorageSync('access_token_expired_at')
}

export function logout() {
  return uni.clearStorage()
}
